<template>
  <a-modal
    :visible="visible"
    title="商机认领"
    @ok="handleOk"
    @cancel="handleCancel"
    :confirmLoading="confirmLoading"
    :maskClosable="false"
  >
    <div class="business-assign-modal">
      <a-form :model="formState" :label-col="{ span: 6 }" :wrapper-col="{ span: 18 }">
        <a-form-item label="商务人员" :rules="[{ required: true, message: '请选择商务人员' }]">
          <a-select
            v-model:value="formState.selectedUserId"
            :options="businessUsers"
            placeholder="请选择商务人员"
            :filter-option="filterOption"
            show-search
            :loading="loading"
          >
            <template #option="{ value: val, label }">
              <div>{{ label }}</div>
            </template>
          </a-select>
        </a-form-item>
      </a-form>
    </div>
  </a-modal>
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted, defineExpose, defineEmits } from 'vue';
import { getBusinessDeptUsers } from '../CustomersPool.api';
import { useMessage } from '/@/hooks/web/useMessage';

const emit = defineEmits(['ok', 'cancel']);
const { createMessage } = useMessage();

// 模态框状态
const visible = ref(false);
const confirmLoading = ref(false);
const loading = ref(false);
const currentRecord = ref({});
const businessUsers = ref([]);

// 表单状态
const formState = reactive({
  selectedUserId: undefined
});

// 过滤选项
const filterOption = (input, option) => {
  return option.label.toLowerCase().indexOf(input.toLowerCase()) >= 0;
};

// 打开模态框
async function open(record) {
  confirmLoading.value = false;
  visible.value = true;
  currentRecord.value = record;
  formState.selectedUserId = undefined;
  
  // 加载商务部门用户
  loading.value = true;
  try {
    const res = await getBusinessDeptUsers();
    console.log('API返回的原始数据:', res);
    if (res && res.result && Array.isArray(res.result)) {
      businessUsers.value = res.result.map(user => ({
        value: user.id,
        label: user.realname,
        userId: user.id,
        realName: user.realname
      }));
      console.log('商务人员列表:', businessUsers.value);
    } else if (res && Array.isArray(res)) {
      businessUsers.value = res.map(user => ({
        value: user.id,
        label: user.realname || user.realName,
        userId: user.id,
        realName: user.realname || user.realName
      }));
      console.log('商务人员列表(直接数组):', businessUsers.value);
    } else {
      businessUsers.value = [];
      createMessage.error('获取商务人员列表失败');
    }
  } catch (error) {
    console.error('获取商务人员列表错误:', error);
    createMessage.error('获取商务人员列表失败: ' + ((error as any).message || '未知错误'));
    businessUsers.value = [];
  } finally {
    loading.value = false;
  }
}

// 确认按钮处理
function handleOk() {
  if (!formState.selectedUserId) {
    createMessage.warning('请选择商务人员');
    return;
  }

  // 检查选择的用户是否在列表中
  const selectedUser = businessUsers.value.find(user => user.value === formState.selectedUserId);
  if (!selectedUser) {
    createMessage.error('所选人员不存在');
    return;
  }

  confirmLoading.value = true;
  emit('ok', selectedUser);
}

// 取消按钮处理
function handleCancel() {
  visible.value = false;
  emit('cancel');
}

// 重置加载状态
function resetConfirmLoading() {
  confirmLoading.value = false;
}

// 对外暴露方法
defineExpose({
  open,
  visible,
  currentRecord,
  resetConfirmLoading
});
</script>

<style lang="less" scoped>
.business-assign-modal {
  padding: 12px 0;
}
</style>